import { useRef, useState, useEffect, RefObject } from 'react'
import { Modal, Form, Input, Select, FormInstance, Switch, message } from 'antd';
import { CaseSchema, PartySchema } from '@src/components/schema/caseSchema'
import Dictionary, { DictionaryItem } from '@js/dictionary';
import { ArbitratorSchema } from '@src/components/schema/arbitrator';
import { emailPattern, awaitWrap } from '@js/tool';
import { EAddressSchema } from '@components/schema/address';
import { addRequest, updateRequest } from './ajax'

const { Item } = Form
const { Option } = Select

async function submitHandle (d: { [k: string]: any }, caseid: string, refreshFn: () => void) {
  let fn = addRequest
  if (d.id) {
    fn = updateRequest
  }
  d.caseid = caseid
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(fn(d))
  h()
  if (e === null) {
    message.success('提交成功')
    refreshFn()
  }
}

// 改变主体
function changeContractId (id: string, formRef: RefObject<FormInstance>, list: PartySchema[]) {
  const c = formRef.current
  const type = c?.getFieldValue('action_subject')
  let obj: { [k: string]: any } = {}
  for (let i = 0; i < list.length; i++) {
    if (list[i].id === id) {
      obj = list[i]
    }
  }
  const data: { [k: string]: any } = {
    contractid: id,
    mobile: obj.mobile,
    address: obj.address,
    type: '',
    tel: obj.tel,
    tel_office: '',
    zip_code: obj.zip_code,
    email: obj.email,
    contract_type: '自然人'
  }
  if (['申请人', '被申请人'].indexOf(type) !== -1) {
    if (['企业', '非法人组织'].indexOf(obj.subject_type) !== -1) {
      data.structure = obj.name
      data.contract = ''
      data.contract_type = obj.subject_type === '企业' ? '法人' : '非法人组织'
    } else {
      data.structure = ''
      data.contract = obj.name
    }
  } else if (type.indexOf('代理人') !== -1) {
    data.structure = ''
    data.contract = obj.name
  } else if (type === '仲裁员') {
    data.contract = obj.name
    data.address = obj.structure_address
    data.tel_office = obj.structure_tel
    data.structure = obj.structure
    data.zip_code = obj.zip
  }
  const keys = Object.keys(data)
  keys.forEach(key => {
    if (!data[key]) {
      data[key] = undefined
    }
  })
  c?.setFieldsValue(data)
}

// 渲染送达类型
function renderSendType (type: string, addressTypes: DictionaryItem[]) {
  if (type !== '仲裁员') {
    return (
      <Item name='type' label='地址类型' rules={[{ required: true, message: '地址类型不能为空' }]}>
        <Select placeholder='请选择地址类型'>
          {
            addressTypes.map(li => {
              return <Option key={li.title} value={li.title}>{li.title}</Option>
            })
          }
        </Select>
      </Item>
    )
  }
}

// 改变主体类型
function changeSubject (
  e: string,
  d: CaseSchema | null,
  arbitrators: ArbitratorSchema[],
  formRef: RefObject<FormInstance>,
  setContractList: (v: PartySchema[]) => void,
  setType: (v: string) => void
) {
  if (d === null) {
    return undefined
  }
  let list: PartySchema[] = []
  switch (e) {
    case '申请人':
      list = d.applicants.filter(li => li.status)
      break
    case '被申请人':
      list = d.respondents.filter(li => li.status)
      break
    case '申请人代理人':
      list = d.applicant_agents
      break
    case '被申请人代理人':
      list = d.respondents_agents
      break
    case '仲裁员':
      list = arbitrators as unknown as PartySchema[]
      break
    default:
      list = []
      break
  }
  setContractList(list)
  setType(e)
  formRef.current?.setFieldsValue({
    action_subject: e
  })
}

interface Props {
  caseDetail: CaseSchema | null
  caseid: string
  arbitrators: ArbitratorSchema[]
  visible: boolean
  data: EAddressSchema | null
  hide: () => void
  refreshFn: () => void
}

function Main ({ caseDetail, arbitrators, caseid, visible, data, hide, refreshFn }: Props) {
  const formRef = useRef<FormInstance>(null)
  const [contractList, setContractList] = useState<PartySchema[]>([])
  const [addressTypes, setAddressTypes] = useState<DictionaryItem[]>([])
  const [type, setType] = useState('')
  useEffect(() => {
    const d = new Dictionary()
    d.init('电子送达地址类型')
      .then(() => {
        setAddressTypes(d.getList('电子送达地址类型'))
      })
      .catch(e => console.error(e))
  }, [])
  useEffect(() => {
    const c = formRef.current
    if (c) {
      if (visible) {
        const d = data ? { ...data, status: data.status === 1 } : { status: 1, address_type: '电子地址' }
        c.setFieldsValue(d)
        if (data) {
          changeSubject(data.action_subject, caseDetail, arbitrators, formRef, setContractList, setType)
        }
      } else {
        c.resetFields()
      }
    }
  }, [data, visible])
  return (
    <div>
      <Modal visible={visible} title={data ? '修改地址' : '新增地址'} onCancel={() => hide()}
        onOk={() => formRef.current?.submit()}
      >
        <Form name='add-service' labelCol={{ span: 4 }} initialValues={{ status: 1, address_type: '电子地址' }} ref={formRef} onFinish={d => submitHandle(d, caseid, () => { refreshFn(); hide(); })}>
          <Item name='action_subject' label='仲裁地位' rules={[{ required: true, message: '仲裁地位不能为空' }]}>
            <Select placeholder='请选择仲裁地位' onChange={e => {
              formRef.current?.resetFields()
              changeSubject(e, caseDetail, arbitrators, formRef, setContractList, setType)
            }}>
              {
                ['申请人', '被申请人', '申请人代理人', '被申请人代理人', '仲裁员'].map(li => {
                  return <Option key={li} value={li}>{li}</Option>
                })
              }
            </Select>
          </Item>
          <Item name='id' noStyle><span /></Item>
          <Item name='address_type' noStyle><span /></Item>
          <Item name='contractid' label='主体' rules={[{ required: true, message: '主体不能为空' }]}>
            <Select placeholder='请选择主体' onChange={e => changeContractId(e, formRef, contractList)}>
              {
                contractList.map(li => {
                  return <Option key={li.id} value={li.id}>{li.name}</Option>
                })
              }
            </Select>
          </Item>
          {renderSendType(type, addressTypes)}
          <Item name='contract' label='收件人'>
            <Input placeholder='请输入收件人' />
          </Item>
          <Item name='contract_type' noStyle><span /></Item>
          {/* <Item name='structure' label='单位'>
            <Input placeholder='请输入单位' />
          </Item> */}
          <Item name='mobile' label='手机号码' rules={[{ required: true, message: '手机号码不能为空' }, { pattern: /^1\d{10}(,1\d{10})*$/, message: '手机号码格式不正确，多个号码请以英文逗号隔开' }]}>
            <Input placeholder='请输入手机号码' />
          </Item>
          <Item name='email' label='邮箱' rules={[{ pattern: emailPattern, message: '邮箱格式不正确，多个邮箱请以英文逗号隔开' }]}>
            <Input placeholder='请输入邮箱' />
          </Item>
          <Item name='status' label='是否有效' valuePropName='checked'>
            <Switch checkedChildren='有效' unCheckedChildren='无效' />
          </Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Main
